package com.hilinos.base.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hilinos.base.common.Constant;
import com.hilinos.base.user.entity.pojo.KeyInfoPoJo;
import com.hilinos.base.mapper.IKeyInfoMapper;
import com.hilinos.base.service.KeyInfoService;
import com.hilinos.common.common.ReturnCode;
import com.hilinos.common.entity.BaseQo;
import com.hilinos.common.util.AssertUtils;
import com.hilinos.common.util.DateUtils;
import com.hilinos.common.util.IdUtils;
import com.hilinos.common.util.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author hilinos
 * @since 2022-03-11
 */
@Service
@Slf4j
public class KeyInfoServiceImpl extends ServiceImpl<IKeyInfoMapper, KeyInfoPoJo> implements KeyInfoService {

    @Override
    public KeyInfoPoJo create(String keyExpTime, Integer keyStatus) {
        String appid = IdUtils.DEFAULT.gen().toString();
        Date keyExpTimeDate = DateUtils.ymdhmsStringToDate(keyExpTime);

        KeyInfoPoJo keyInfo = KeyInfoPoJo.builder()
                .keyAppid(appid)
                .keyType(Constant.SU_USER_TYPE_USER)
                .keySecret(RandomUtils.genRandomStr(24))
                .keyExpTime(keyExpTimeDate)
                .keyStatus(keyStatus)
                .build();

        save(keyInfo);

        return keyInfo;
    }

    @Override
    public boolean isAdmin(String appid) {
        KeyInfoPoJo keyInfo = getById(appid);
        AssertUtils.isNotEmpty(keyInfo, ReturnCode.AUTH_ERROR);
        return Constant.SU_USER_TYPE_ADMIN.equals(keyInfo.getKeyType());
    }

    @Override
    public IPage<KeyInfoPoJo> pageList(BaseQo<KeyInfoPoJo, KeyInfoPoJo, KeyInfoPoJo> qo) {
        return page(qo.page(), qo.queryWrapper());
    }

    @Override
    public void edit(KeyInfoPoJo keyInfoPoJo) {
        updateById(keyInfoPoJo);
    }

}